import Vue from "vue";
import Router from "vue-router";
import store from "@/store";
import _import from "./_import";
import { RouterMeta } from "./app";
import "./hooks";
import { getPermissionList } from "./check-auth";

/* 包含导航栏的布局入口 */
import BaseLayout from "@/views/layout/index.vue";
import ExampleLayout from "@/views/layout/example.vue";
import NoMenuLayout from "@/views/layout/no-menu.vue";
import AuthLayout from "@/views/layout/auth.vue";
import DefaultLayout from "@/views/layout/default.vue";

import { RouterConfig as MenuConfig } from "./map.router.config";
/* 登录用户 */
import { UserRouters } from "@/router/user.router";
import {
    OrgRouters,
    RouterConfig as OrganizationConfig
} from "@/router/organization.router";
import {
    ResourceRouters,
    RouterConfig as ResourceConfig
} from "@/router/resource.router";
import { TaskRouters } from "@/router/task.router";
import {
    SYSTEMRouters,
    RouterConfig as SystemConfig
} from "@/router/system.router";
import {
    ProcessRouters,
    RouterConfig as ProcessConfig
} from "@/router/process.router";
import {
    DataRetrievalRouters,
    RouterConfig as DataRetrievalConfig
} from "@/router/data.retrieval.router";
import AuthRouters, { RouterConfig as AuthConfig } from "@/router/auth.router";
import ExampleRouters, {
    RouterConfig as ExampleConfig
} from "@/router/example.router";
import ModuleManageRouters, {
    RouterConfig as ModuleManageConfig
} from "@/router/module-manage.router";
import {
    projectManageRoutes,
    RouterConfig as projectManageConfig
} from "@/router/projectManage.router";
import {
    DeclareRouters,
    RouterConfig as DeclareManageConfig
} from "@/router/declare.router";
import {
    ImportCreateRouters,
    RouterConfig as ImportCreateConfig
} from "@/router/import.create.router";

import { AllResourceData } from "@/router/all-resource-data.router";

// import Home from "@/views/home";
// 这是懒加载加载的路由
const ErrorPage404 = () =>
    import(
        /* webpackChunkName: "error-page-404" */ "@/views/error-page/404.vue"
    );
export const AllRouterConfig: any = {
    ...MenuConfig,
    ...AuthConfig,
    ...ExampleConfig,
    ...ModuleManageConfig,
    ...OrganizationConfig,
    ...ResourceConfig,
    ...SystemConfig,
    ...ProcessConfig,
    ...DataRetrievalConfig,
    ...projectManageConfig,
    ...DeclareManageConfig,
    ...AllResourceData,
    ...ImportCreateConfig
};
export const getRouterConfig = (name: any) => {
    const _authArea: any = store.getters.getAuthArea;
    if (_authArea && _authArea.level && AllRouterConfig[name]) {
        return (
            AllRouterConfig[name][_authArea.level.name] ||
            AllRouterConfig[name].DEFAULT ||
            {}
        );
    }
    return {};
};
// 这是需要判断权限的路由列表
export const AsyncRoutersMap: any[] = [
    {
        path: "/",
        component: BaseLayout, // 通过这个入口区分哪些页面不需要顶部bar和左侧导航栏
        children: [
            {
                path: "organization",
                component: _import("organization/index.vue"),
                name: "Organization",
                meta: {
                    title: "组织架构",
                    icon: "icon-not-org",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta,
                children: OrgRouters
            },
            {
                path: "resource-manage",
                component: _import("resource-manage/index.vue"),
                name: "Resource",
                meta: {
                    title: "运营管理",
                    icon: "icon-not-opr",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta,
                children: ResourceRouters
            },
            {
                path: "all-resource-data",
                component: _import("all-resource-data/index.vue"),
                name: "PlatformData",
                meta: {
                    title: "全平台数据统计",
                    icon: "icon-not-opr",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta,
                children: AllResourceData
            },
            {
                path: "task-manage",
                component: _import("task-manage/index.vue"),
                name: "Task",
                meta: {
                    title: "任务管理",
                    icon: "icon-not-task",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta,
                children: TaskRouters
            },
            {
                path: "module-manage",
                component: _import("module-manage/index.vue"),
                name: "ModuleManage",
                redirect: "module-manage/home",
                meta: {
                    title: "业务流程",
                    icon: "icon-not-file",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta,
                children: ModuleManageRouters
            },
            {
                path: "system-manage",
                component: _import("system-manage/index.vue"),
                name: "SystemManage",
                meta: {
                    title: "系统管理",
                    icon: "icon-not-home",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta,
                children: SYSTEMRouters
            },
            {
                path: "process-manage",
                component: _import("system-manage/index.vue"),
                name: "ProcessManage",
                meta: {
                    title: "流程管理",
                    icon: "icon-not-home",
                    requiresAuth: false,
                    isMenu: true,
                    filter: true
                } as RouterMeta,
                children: ProcessRouters
            },
            {
                path: "data-retrieval",
                component: _import("data-retrieval/index.vue"),
                name: "DataRetrieval",
                meta: {
                    title: "数据检索",
                    icon: "icon-not-home",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta,
                children: DataRetrievalRouters
            },
            {
                path: "projectManage",
                component: _import("project-manage/index.vue"),
                name: "ProjectManage",
                meta: {
                    title: "项目管理",
                    icon: "icon-not-file",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta,
                children: projectManageRoutes
            },
            {
                path: "declare-manage",
                component: _import("declare-manage/index.vue"),
                name: "DeclareManage",
                meta: {
                    title: "上报管理",
                    icon: "icon-not-file",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta,
                children: DeclareRouters
            },
            {
                path: "village-team-info",
                component: _import("village-team-info/index.vue"),
                name: "village-team-info",
                meta: {
                    title: "村组信息",
                    icon: "icon-not-home",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta
            },
            {
                path: "village-town-info",
                component: _import("village-town-info/index.vue"),
                name: "village-town-info",
                meta: {
                    title: "村镇信息",
                    icon: "icon-not-home",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta
            },
            {
                path: "resource-map",
                component: _import("resource-map/index.vue"),
                name: "resource-map",
                meta: {
                    title: "资源地图",
                    icon: "icon-not-home",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta
            },
            {
                path: "resource-view",
                component: _import("village-town-resource-view/index.vue"),
                name: "resource-view",
                meta: {
                    title: "资源视图",
                    icon: "icon-not-home",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta
            },
            {
                path: "resource-reminder",
                component: _import("resource-reminder/index.vue"),
                name: "resource-reminder",
                meta: {
                    title: "资源提醒",
                    icon: "icon-resource-reminder",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta
            },
            {
                path: "user-list",
                component: _import("user-list/src/list.vue"),
                name: "UserList",
                meta: {
                    title: "用户列表",
                    icon: "icon-not-home",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta
            },
            {
                path: "overview",
                component: _import("overview/src/index.vue"),
                name: "Overview",
                meta: {
                    title: "概览",
                    icon: "icon-not-overview",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta
            },
            {
                path: "import-create",
                component: _import("import-create/index.vue"),
                name: "ImportCreate",
                meta: {
                    title: "导入创建",
                    icon: "icon-not-overview",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true,
                    onlyOne: true
                } as RouterMeta,
                children: ImportCreateRouters
            }
        ]
    },
    {
        path: "/",
        component: NoMenuLayout, // 通过这个入口区分哪些页面不需要顶部左侧导航栏
        children: [
            {
                path: "user",
                component: _import("user/index.vue"),
                name: "User",
                meta: {
                    title: "用户模块",
                    requiresAuth: true,
                    isMenu: false,
                    onlyOne: false
                } as RouterMeta,
                children: UserRouters
            }
        ]
    },
    {
        path: "/",
        component: DefaultLayout,
        children: [
            {
                path: "townView",
                component: _import("town-view/index.vue"),
                name: "TownView",
                meta: {
                    title: "全镇视图",
                    icon: "icon-not-home",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta
            }
        ]
    },
    {
        path: "*",
        redirect: "/404"
    }
];
// 这是路由的列表
export const AllRoutersMap: any[] = [
    {
        path: "/",
        component: BaseLayout, // 通过这个入口区分哪些页面不需要顶部bar和左侧导航栏
        children: [
            {
                path: "",
                component: _import("home/index.vue"),
                name: "home",
                meta: {
                    title: "概览",
                    icon: "icon-not-home",
                    requiresAuth: true,
                    isMenu: true,
                    filter: true
                } as RouterMeta
            }
            // {
            //     path: "1",
            //     component: _import("home/index1.vue"),
            //     name: "home2",
            //     meta: {
            //         title: "首页2",
            //         requiresAuth: true,
            //         isMenu: true
            //     } as RouterMeta
            // },
            // {
            //     path: "2",
            //     component: _import("home/index2.vue"),
            //     name: "home3",
            //     meta: {
            //         title: "首页3",
            //         requiresAuth: true,
            //         isMenu: true
            //     } as RouterMeta
            // },
        ]
    },
    {
        path: "/",
        component: AuthLayout,
        children: [
            {
                path: "auth",
                name: "Auth",
                component: _import("auth/index.vue"),
                redirect: "/auth/login",
                meta: {
                    title: "登录模块",
                    requiresAuth: false
                } as RouterMeta,
                children: AuthRouters
            }
        ]
    },
    {
        path: "/example",
        component: ExampleLayout,
        children: ExampleRouters
    },
    {
        // TODO remove 用于概览重定向，以后删除
        path: "/home",
        redirect: "/"
    },
    {
        path: "/404",
        name: "404",
        component: ErrorPage404,
        meta: {
            title: "404",
            icon: "icon-merchant",
            requiresAuth: false
        } as RouterMeta
    }
];
Vue.use(Router);
const createRouter = () => {
    return new Router({
        // mode: 'history', // require service support
        routes: AllRoutersMap
    });
};

const router: any = createRouter();

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
    const newRouter: any = createRouter();
    router.matcher = newRouter.matcher; // reset router
}

const beforeEach = async(toRoute: any, fromRoute: any, next: any) => {
    const _routeConfig: any = getRouterConfig(
        (toRoute.meta && toRoute.meta.aliasName) || toRoute.name
    );
    if (_routeConfig.title) {
        toRoute.meta.title = _routeConfig.title;
    }
    if (toRoute.meta.title) {
        document.title = toRoute.meta.title + "·乡村资源管理交易平台";
    }
    // 这部分是封装在vuex里面的用户登录状体
    const user = store.getters.getUser;
    const dynamicRouterRequest = store.getters.getDynamicRouterRequest;
    // const dynamicRouterRequest = true;
    if (user.isSignIn) {
        if (toRoute.name === "AuthLogin") {
            next({
                name: "home",
                replace: true
            });
            return;
        }
        if (dynamicRouterRequest) {
            const _authArea: any = store.getters.getAuthArea;
            const _authHistory: any = store.getters.getAuthHistory;
            // 只有管理员能跳，跳转调用switch接口后会到"/"去，统一拦截判断,镇普通哪儿都能去
            if (
                toRoute.name === "home" &&
                (["3", "5", "7"].includes(_authArea.orgCategoryId) ||
                    _authHistory.list.length > 1) &&
                _authArea.orgCategorySourceId !== "7"
            ) {
                const url = await store.dispatch("defaultPage");
                next({
                    path: url,
                    replace: true
                });
                return;
            }
            next();
            return;
        }
        store
            .dispatch("dynamicMenuRouter")
            .then(r => {
                if (r.data.code !== 200) {
                    if (fromRoute.name === "AuthLogin") {
                        next(false);
                    } else {
                        next({
                            path: "/auth/login",
                            replace: true,
                            query: {
                                redirect: toRoute.fullPath
                            }
                        });
                    }
                    return;
                }
                // const _dynamicMenuRouters = [
                //     {
                //         path: "",
                //         component: BaseLayout, // 通过这个入口区分哪些页面不需要顶部bar和左侧导航栏
                //         children: r.data.data.router.base
                //     },
                //     {
                //         path: "",
                //         component: AuthLayout, // 通过这个入口区分哪些页面不需要顶部bar和左侧导航栏
                //         children: r.data.data.router.auth
                //     },
                //     {
                //         path: "*",
                //         redirect: "/404"
                //     }
                // ];
                // resetRouter();
                const routerList: any[] = getPermissionList(AsyncRoutersMap);
                router.addRoutes(routerList);
                next({ ...toRoute, replace: true });
            })
            .catch(() => {
                store.dispatch("logout").then(() => {
                    next({
                        path: "/auth/login",
                        replace: true,
                        query: {
                            redirect: toRoute.fullPath
                        }
                    });
                });
            });
    } else {
        if (!toRoute.name || toRoute.meta.requiresAuth) {
            next({
                path: "/auth/login",
                replace: true,
                query: {
                    redirect: toRoute.fullPath
                }
            });
        } else {
            next();
        }
    }
};
// const afterEach = (toRoute: any, fromRoute: any) => {
// };
const beforeResolve = (to: any, from: any, next: any) => {
    // const _authArea: any = store.getters.getAuthArea;
    // if (_authArea && _authArea.level && AllRouterConfig[to.name] && AllRouterConfig[to.name][_authArea.level.name]) {
    //     to.meta.title = AllRouterConfig[to.name][_authArea.level.name].title || to.meta.title;
    // }
    next();
};
router.beforeEach(beforeEach);
router.beforeResolve(beforeResolve);
// router.afterEach(afterEach);

export default router;
